package com.wondersgroup.fjzlpt.plat.controller.view;

import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.auth.login.LoginService;
import com.wondersgroup.fjzlpt.plat.feign.CertFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 * Created by lion on 2017/5/21.
 */
@Controller
public class LoginController {

    /**认证域的key*/
    @Value("${common.domainKey}")
    private String domainKey;

    @Autowired
    private LoginService loginService;
    @Autowired
    private CertFeignService certService;

    @Value(("${common.cookie.max-age}"))
    private int cookieMaxAge;

    @RequestMapping("ignore/login.html")
    public String toLogin(HttpServletRequest request)
    {
        request.setAttribute("domainKey", domainKey);
        return "login/login";
    }

    /**
     * 用户登录
     * @param request
     */
    @RequestMapping("ignore/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            String username = request.getParameter("USERNAME");
            String password = request.getParameter("PASSWORD");
            String fromUrl = request.getParameter("fromUrl");

        /*查询用户唯一ID*/
            String userUniqueId = loginService.queryUserUniqueId(username, password);
            if(StringUtils.isEmpty(userUniqueId)) {
                setLoginFailRequestInfo(request, "用户名密码错误");
                forwardLogin(request, response);
            }else{
                /*查询用户信息*/
                Map map = new HashMap(1);
                map.put("USERID", userUniqueId);
                JSONObject userInfo = this.loginService.queryUserInfo(map);
                if(userInfo.isEmpty()){
                    setLoginFailRequestInfo(request, "未查询到用户信息，请联系管理员确认账号");
                    forwardLogin(request, response);
                }else{
                    JSONObject roleInfo = this.loginService.queryUserRoleInfo(map);
                    if(roleInfo.isEmpty()){
                        setLoginFailRequestInfo(request, "未查询到用户的角色信息，请联系管理员授权");
                        //forwardLogin(request, response);
                    }else{
                        String roleId = roleInfo.getString("ROLEID");
                        /*添加域认证*/
                        JSONObject domainInfo = addCert(userUniqueId, userInfo, roleId, roleInfo);
                        /*添加成功*/
                        if(domainInfo.getBoolean("state")){
                            String domainId = domainInfo.getString("domainId");
                            Cookie cookie = new Cookie(domainKey, domainId);
                            cookie.setPath("/");
                            cookie.setMaxAge(cookieMaxAge);
                            response.addCookie(cookie);
                            /*登录成功 跳转主页*/
                            if(!StringUtils.isEmpty(fromUrl)){
                                response.sendRedirect(fromUrl);
                            }else{
                                response.sendRedirect("/plat/index.html");
                            }
                        }else{
                            setLoginFailRequestInfo(request, "域认证失败，请联系管理员授权");
                            forwardLogin(request, response);
                        }
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException("中心认证失败", e);
        }
    }

    private JSONObject addCert(String userUniqueId, JSONObject userInfo, String roleId, JSONObject roleInfo){
        //return certService.addCert(domainKey, userUniqueId, userInfo.toString(), roleId, roleInfo.toString());
        JSONObject json = new JSONObject(5);
        json.put("domainKey", domainKey);
        json.put("userUniqueId", userUniqueId);
        json.put("userInfo", userInfo.toString());
        json.put("roleId", roleId);
        json.put("roleInfo", roleInfo.toString());
        return certService.addCert(json);
    }

    private void forwardLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("login.html").forward(request, response);
    }

    private void setLoginFailRequestInfo(HttpServletRequest request, String info){
        request.setAttribute("state", "false");
        request.setAttribute("info", info);
    }
}
